/*  Game/Army Editor for yALB - Yet Another List Builder (roster Editor for Wargames/tabletop games).
    Copyright (C) 2008-2012  Daniel Ricardo Castro Alvarado

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

#include "optionwidget.h"
#include "ui_optionwidget.h"

#include "other/modelcommon.h"
#include "other/categorizermodel.h"
#include "widgets/itemselector.h"

#include <QDebug>
#include <QMessageBox>


OptionWidget::OptionWidget(OptionCollection *_options, CategorizerModel *_optionModel, ItemSelector &_itemSelector,
                           QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OptionWidget)
{
    Q_ASSERT(_options && _optionModel);
    ui->setupUi(this);

    options = _options;
    optionModel = _optionModel;
    ui->optList->setModel(optionModel);
    ui->optCategory->setModel(optionModel);
    ui->scrollArea->setAlignment(Qt::AlignCenter);

    connect(ui->optList->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            this, SLOT(currentItemChanged(QModelIndex,QModelIndex)));
}

OptionWidget::~OptionWidget()
{
    delete ui;
}

void OptionWidget::clearOptionForm() {
    ui->actionBox->clearActionForm();
    ui->optState->setCurrentIndex(0);
    ui->optName->setText("");
    ui->optKey->setText("");
    ui->optRequired->setText("");
    ui->optCost->setValue(0.0);
    ui->optPointsPerMiniature->setChecked(false);
}

void OptionWidget::currentItemChanged(const QModelIndex& current, const QModelIndex& previous)
{
    Q_UNUSED(previous)
    propertyForm.clearAllValues();
    propertyForm.savePropertyValues();
    if(current.isValid() && !optionModel->isCategory(current)) {
        QString key = current.data(ModelCommon::KeyRole).toString();
        UnitOption option = options->get(key);

        ui->optCategory->setCurrentIndex(current.parent().row());
        ui->optState->setCurrentIndex(int(option.state));
        ui->optName->setText(option.getName());
        ui->optKey->setText(key);
        ui->optRequired->setText(option.required);
        ui->optCost->setValue(option.getCost());
        ui->optPointsPerMiniature->setChecked(option.costPerMin);

        ui->actionBox->setActions(option.actions);

        ui->optDelete->setEnabled(true);
        ui->optUpdate->setEnabled(true);
        ui->optClone->setEnabled(true);

        // Set up PropertyForm

        QHash<QString, QString>::const_iterator i;
        for(i = option.properties.constBegin();
            i != option.properties.constEnd(); ++i)
            propertyForm.setPropertyValue(i.key(), i.value());

        ui->optPropertiesBox->setEnabled(true);

    } else {
        clearOptionForm();
        ui->optCategory->setCurrentIndex(current.row());
        ui->optDelete->setEnabled(false);
        ui->optUpdate->setEnabled(false);
        ui->optClone->setEnabled(false);

        ui->optPropertiesBox->setEnabled(false);
    }
}

void OptionWidget::on_optAdd_clicked()
{
    UnitOption option(ui->optCategory->itemData(ui->optCategory->currentIndex(), Qt::UserRole).toString(),
                      GameStructs::getOptionStateFromInt(ui->optState->currentIndex()),
                      ui->optName->text(), (float)ui->optCost->value(), ui->optPointsPerMiniature->isChecked(),
                      ui->optRequired->text(), ui->actionBox->getActions(), QHash<QString, QString>());
    options->add(option, ui->optKey->text());
}

void OptionWidget::on_optUpdate_clicked()
{
    QModelIndex current = ui->optList->currentIndex();

    Q_ASSERT(current.isValid() && !optionModel->isCategory(current));

    QString key = current.data(ModelCommon::KeyRole).toString();
    UnitOption oldOption = options->get(key);
    UnitOption option(ui->optCategory->itemData(ui->optCategory->currentIndex(), ModelCommon::KeyRole).toString(),
                      GameStructs::getOptionStateFromInt(ui->optState->currentIndex()),
                      ui->optName->text(), (float)ui->optCost->value(), ui->optPointsPerMiniature->isChecked(),
                      ui->optRequired->text(), ui->actionBox->getActions(), oldOption.properties);
    options->update(key, option, ui->optKey->text());
}

void OptionWidget::on_optDelete_clicked()
{
    if(QMessageBox::warning(0, tr("Are you sure?"), tr("Deleting an option will make invalid all values that use it. Are you sure you want to continue?"),
                            QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
        options->remove(ui->optList->currentIndex().data(ModelCommon::KeyRole).toString());
}

void OptionWidget::on_optClone_clicked()
{
    QModelIndex current = ui->optList->currentIndex();

    Q_ASSERT(current.isValid() && !optionModel->isCategory(current));

    QString key = current.data(ModelCommon::KeyRole).toString();
    options->cloneKey(key);
}

void OptionWidget::on_optSetPropertiesButton_clicked()
{
    if(propertyForm.exec() == QDialog::Accepted) {
        QModelIndex current = ui->optList->currentIndex();

        Q_ASSERT(current.isValid() && !optionModel->isCategory(current));

        QString key = current.data(ModelCommon::KeyRole).toString();

        UnitOption option = options->get(key);
        option.properties = propertyForm.getProperties();
        options->update(key, option, key);
    }
}

void OptionWidget::changeEvent(QEvent *event) {
    if(event->type() == QEvent::LanguageChange)
        ui->retranslateUi(this);
    QWidget::changeEvent(event);
}
